<template>
  <div class="container">
    <h2>宝宝信息管理</h2>
    <div class="baby-info">
      <div class="form-group">
        <label>宝宝姓名：</label>
        <input type="text" v-model="babyInfo.name">
      </div>
      <div class="form-group">
        <label>出生时间：</label>
        <input type="datetime-local" v-model="babyInfo.birthdate">
      </div>
      <button @click="saveBabyInfo" class="save-button">保存信息</button>
    </div>
    
    <!-- <div v-if="lastUpdate" class="update-info">
      最后更新时间：{{ formatDateTime(lastUpdate) }}
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'

const babyInfo = ref({
  name: '',
  birthdate: dayjs().format('YYYY-MM-DDTHH:mm')
})
const lastUpdate = ref(null)

onMounted(async () => {
  try {
    const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/baby`)
    if (response.data.name) {
      babyInfo.value = {
        name: response.data.name,
        birthdate: dayjs(response.data.birthdate).format('YYYY-MM-DDTHH:mm')
      }
      lastUpdate.value = response.data.birthdate
    }
  } catch (error) {
    console.error('获取宝宝信息失败:', error)
  }
})

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

const saveBabyInfo = async () => {
  try {
    const payload = {
      name: babyInfo.value.name,
      birthdate: dayjs(babyInfo.value.birthdate).format('YYYY-MM-DD HH:mm')
    }
    await axios.put(`${import.meta.env.VITE_API_BASE_URL}/api/baby`, payload)
    lastUpdate.value = new Date()
    alert('信息保存成功！')
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  }
}
</script>

<style scoped>
.container {
  padding: 15px;
  margin-top: 10px;
  margin-bottom: 60px; /* 为底部导航栏留出空间，调整为60px以适应导航栏 */
}

h2 {
  font-size: 36px;
  margin-bottom: 20px;
  text-align: center;
  color: #2c3e50;
}

.baby-info {
  max-width: 350px;
  margin: 0 auto;
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 6px;
  font-weight: bold;
  color: #2c3e50;
  font-size: 18px;
}

input[type="text"],
input[type="datetime-local"] {
  width: 100%;
  padding: 12px 15px;
  margin-top: 5px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 18px;
  box-sizing: border-box;
}

.save-button {
  background: #2196F3;
  color: white;
  padding: 12px 15px;
  border: none;
  border-radius: 8px;
  margin-top: 15px;
  width: 100%;
  font-size: 20px;
  font-weight: bold;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.update-info {
  margin-top: 15px;
  color: #666;
  text-align: center;
  font-size: 18px;
}
</style>